<template>
  <div>
    <FormPanel  ref="formPanel"
        :formType="formType"
        :list="initForm"
        :cols="3"
        :labelWidth="120"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
        class="mtop"
     />
     <div class="dialogBottmView">
      <el-button @click="closeDialog">取 消</el-button>
      <MultiuseButton :click="saveDialog" type="primary">保 存</MultiuseButton>
    </div>
       <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="visibleModelDlg"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <modalDlg selectType="multiple" @close="selectModelBack" />
    </BaseDialog>
  </div>

</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { phone } from '@/utils/validate' // 验证
import { insertClub, updateClub, getClubById } from '@/api/cms-api/customerManage/clue/createClue';
import { getModel,toSelectData } from '@/api/cms-common/basedata';
import { region } from '@/api/cms-common/region';
import modalDlg  from '@/pages/cms-common/model'
import { Notification } from 'element-ui';
import { parseTime } from '@/utils';
export default {
  mixins: [dictionary,region],
  components: {
    modalDlg
  },
  data() {
    return {
      oldData: {},
      formType : 'add',
      visibleModelDlg : false,
      modelId : '',//意向车型ID
      initForm : this.initFormFun(),
      formValue : {},
      cityData: {}
    };
  },
  methods: {
    //初始化数据
    async init(data){
     this.formValue={};
     this.formType = data.type;
     
     if(data.type==='edit'){
       
       let clueData = await getClubById(data.row['clueId']);
       let {...showData} = clueData;
       this.modelId = showData.data.intentionModel;
       //初始化是否全国上牌
       let lps = showData.data.licenseProvinces;//上牌省份
       let isLicenseAll = showData.data.isLicenseAll;//是否全国上牌
       if(isLicenseAll==10041001){//全国上牌
          this.initForm.find(item => item.fieldName==='licenseProvinces').type = 'MULTIPLE_SELECT';
          //上牌城市不可编辑
          this.initForm.find(item => item.fieldName === 'licenseCity').disabled = true;
          //将字符串修改为数字数组
          let lpaInitArray = [];
          if(lps!=null && typeof(lps)!='undefined' && lps!=''){
             lpaInitArray = lps.split(",");
             if(lpaInitArray!=null && lpaInitArray.length>0){
               for(let k=0;k<lpaInitArray.length;k++){
                 lpaInitArray[k] = parseInt(lpaInitArray[k]);
               }
             }
          }
          showData.data.licenseProvinces = lpaInitArray;
       }else{
         if(lps!=null && typeof(lps)!='undefined' && lps!=''){
           showData.data.licenseProvinces = parseInt(lps);
         }
       }
       this.initForm.forEach(x => {
            x.initialValue = showData.data[x.fieldName];
        });
        this.oldData = showData.data;
        //初始化所在市，区
        this.initCity(this.oldData['customerProvince']);
        this.initTown(this.oldData['customerCity']);
        //初始化所在上牌市
        this.initLicenseCity(this.oldData['licenseProvinces']);
      }else if(data.type = 'add'){
        //新增时，建档日期默认为当前日期
        //this.initForm[5].initialValue = parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}');
        this.initForm.find(item => item.fieldName==='recordDate').initialValue = parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}');
      }
    },
    //搜索数据
    initFormFun(){
        return [{//1
              type: 'INPUT',
              label: '客户公司名称',
              fieldName: 'customerName',
              placeholder: '请输入',
              initialValue: '',
              rules: [{
                required: true,
                message: '必填',
                trigger: 'blur'
              },{ max: 200, message: '长度最大200字符', trigger: 'blur' }]
            },
            {//2
              type: 'SELECT',
              label: '客户类型',
              fieldName: 'customerType',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2506')
            },
            {//3
              type: 'SELECT',
              label: '客户性质',
              fieldName: 'customerProperty',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2534')
            },
            {//4
              type: 'SELECT',
              label: '客户状态',
              fieldName: 'customerStatus',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2507')
            },
            {//5
              type: 'SELECT',
              label: '客户来源',
              fieldName: 'customerSource',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2508')
            },
            {//6
              type: 'DATE',
              label: '建档时间',
              fieldName: 'recordDate',
              valueFormat: 'yyyy-MM-dd',
              initialValue: '',
              placeholder: '请选择'
            },
            {//7
              type: 'SELECT',
              label: '所在省',
              fieldName: 'customerProvince',
              placeholder: '请选择',
              initialValue: "",
              change: (value) => {
                //清除市信息
                this.initForm.find(item => item.fieldName === 'customerCity').itemList = [];
                this.initForm.find(item => item.fieldName === 'customerCity').initialValue = '';
                //清除县信息
                this.initForm.find(item => item.fieldName === 'customerDistrict').itemList = [];
                this.initForm.find(item => item.fieldName === 'customerDistrict').initialValue = '';
                this.initCity(value);
              },
              itemList:  [],
              rules: [{
                required: true,
                message: '必填',
                trigger: 'blur'
              }]
            },
            {//8
              type: 'SELECT',
              label: '所在市',
              fieldName: 'customerCity',
              placeholder: '请选择',
              initialValue: "",
              itemList: [],
              change: (value) => {
                //清除县信息
                this.initForm.find(item => item.fieldName === 'customerDistrict').itemList = [];
                this.initForm.find(item => item.fieldName === 'customerDistrict').initialValue = '';
                this.initTown(value);
              },
            },
            {//9
              type: 'SELECT',
              label: '所在县/区',
              fieldName: 'customerDistrict',
              placeholder: '请选择',
              initialValue: "",
              itemList:  []
            },
            {//10
              type: 'TEXT_AREA',
              label: '详细地址',
              fieldName: 'customerAddress',
              rows: 1,
              initialValue: '',
              selfCols: 2,
              placeholder: '请输入',
              rules: [{ max: 200, message: '长度最大200字符', trigger: 'blur' }]
            },
            {//11
              type: 'SELECT',
              label: '客户等级',
              fieldName: 'customerLevel',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2509')
            },
            {//12
              type: 'SELECT',
              label: '所属行业分类',
              fieldName: 'industryCategory',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2510')
            },
            {//13
              type: 'SELECT',
              label: '行业地位',
              fieldName: 'industryStatus',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2511')
            },
            {//14
              type: 'SELECT',
              label: '客户采购方式',
              fieldName: 'purchaseMode',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2512')
            },
            {//15
              type: 'INPUT',
              label: '意向车型',
              fieldName: 'intentionModelName',
              placeholder: '请选择',
              initialValue: '',
              rows: 2,
              selfCols: 3,
              readonly : true,
              unitRender: () => {
                    return <el-button slot="append" icon="el-icon-search" onClick={() =>this.openModelDialog()}></el-button>
              },
            },
            {//16
              type: 'INPUT_NUMBER',
              label: '预计采购数量',
              fieldName: 'estimatePurchaseNum',
              placeholder: '请输入',
              initialValue: 0,
              precision:0,
              max:99999999
            },
            {//17
              type: 'SELECT',
              label: '购车用途',
              fieldName: 'buyPurpose',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2513')
            },
            {//18
              type: 'DATE',
              label: '预计采购日期',
              fieldName: 'estimatePurchaseDate',
              valueFormat: 'yyyy-MM',
              dateType:'month',
              initialValue: '',
              placeholder: '请选择'
            },
            {//19
              type: 'SELECT',
              label: '预算来源',
              fieldName: 'budgetSource',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('2514')
            },
            {//20
              type: 'INPUT_NUMBER',
              label: '年度预算',
              fieldName: 'yearBudget',
              placeholder: '请输入',
              offsetRightCols: 1,
              initialValue: 0,
              precision: 2,
              max:9999999999999999
            },
            {//23
              type: 'SELECT',
              label: '是否全国上牌',
              fieldName: 'isLicenseAll',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('1004'),
              rules: [{
                required: true,
                message: '必填',
                trigger: 'blur'
              }],
              change : this.isLicenseAllChange
            },
            {//21
              type: 'SELECT',
              label: '上牌省份',
              fieldName: 'licenseProvinces',
              placeholder: '请选择',
              initialValue: "",
              itemList: [],
              change: (value) => {
                //清除市信息
                this.initForm.find(item => item.fieldName === 'licenseCity').itemList = [];
                this.initForm.find(item => item.fieldName === 'licenseCity').initialValue = '';
                //是否全国上牌
                let isLicenseAll = this.formValue.isLicenseAll;
                if(typeof(isLicenseAll)=='undefined' || isLicenseAll != 10041001){//非全国下发时更新上牌城市，全国下发时，上牌城市不可选。
                  this.initLicenseCity(value);
                }
              }
            },
            {//22
              type: 'SELECT',
              label: '上牌城市',
              fieldName: 'licenseCity',
              placeholder: '请选择',
              initialValue: "",
              itemList: []
            },
            {//23
              type: 'SELECT',
              label: '是否跨区销售',
              fieldName: 'isCrossSbu',
              placeholder: '请选择',
              initialValue: "",
              itemList: this.createDictList('1004')
            },
            {//24
              type: 'INPUT',
              label: '融资渠道',
              fieldName: 'financeChannel',
              placeholder: '请输入',
              initialValue: '',
              rules: [{ max: 100, message: '长度最大100字符', trigger: 'blur' }]
            },
            {//25
              type: 'INPUT',
              label: '客户关键联系人',
              fieldName: 'keyLinkMan',
              placeholder: '请输入',
              initialValue: '',
              rules: [{
                required: true,
                message: '必填',
                trigger: 'blur'
              },{ max: 100, message: '长度最大100字符', trigger: 'blur' }]
            },
            {//26
              type: 'INPUT',
              label: '联系方式',
              fieldName: 'linkPhone',
              placeholder: '请输入',
              initialValue: '',
              rules: [{
                required: true,
                message: '必填',
                trigger: 'blur'
              }, {
                pattern: /^(([1][3,4,5,7,8][0-9]{9})|([0][1-9]{1}[0-9]{1,2}-[0-9]{5,10}))$/,
                message: '手机格式不正确',
                trigger: 'blur'
              }]
            },
            {//26
              type: 'TEXT_AREA',
              label: '备注',
              fieldName: 'remark',
              rows: 2,
              selfCols: 3,
              initialValue: '',
              placeholder: '请输入',
              rules: [{ max: 200, message: '长度最大200字符', trigger: 'blur' }]
            }
          ]
    },
    formChangeHandle(val){
      this.formValue = val;
    },
    //保存或修改线索信息
    async saveClue(postData){
      postData.intentionModel = this.modelId;
      if(this.formType=='add'){
        let res = await insertClub(postData);
        this.ajaxBackDeal(res);
      } else {
        let res = await updateClub(this.oldData['clueId'],postData);
        this.ajaxBackDeal(res);
      }
    },
    //保存
    async saveDialog(){
      //this.$refs.formPanel.SUBMIT_FORM();
        let r = await this.$refs.formPanel.GET_FORM_DATA();
        let p = null;
        if(r!=null && r.length>1){
          let isPassValid = r[0];//是出现异常
          p = Object.assign({},r[1]);
          //将上牌省份处理为以“，”分割的字符串
          let lpArray = p.licenseProvinces;
          let isLicenseAll = p.isLicenseAll;//是否全国上牌
          if(isLicenseAll==10041001){//全国上牌，上牌省份为数组
              if(lpArray!=null && typeof(lpArray)!='undefined' && lpArray.length>0){
                  p.licenseProvinces = lpArray.join(",");
              }else{
                p.licenseProvinces = '';
              }
          }
          //保证数据可以正常的填写进去
          if(String(p.estimatePurchaseDate).indexOf("-01 00:00:00") == -1){
            p.estimatePurchaseDate = p.estimatePurchaseDate + "-01 00:00:00";
          }
          if(!isPassValid)
    	    await this.saveClue(Object.assign({},p));
         }
    },
    //关闭窗口并传参
    ajaxBackDeal(res){
        if(res.resultCode=='200'){
            Notification.success({
              title: `提示信息`,
              message: `保存成功！`
            });
            this.$emit('close', {visible:false,data:this.formValue,type:"refresh"});
        }
    },
    //取消操作
    closeDialog(){
      this.$emit('close', {visible:false});
    },
    //初始化意向车型
    async initModel(){
      let s = await getModel({});
      //this.initForm[14].itemList = toSelectData(s.data,'modelId','modelName');
      this.initForm.find(item => item.fieldName==='intentionModelName').itemList = toSelectData(s.data,'modelId','modelName');
    },
    //初始化所在省份
    async initProvince(){
      let pl = await this.createRegionList();
      //this.initForm[6].itemList = pl;
      //this.initForm[20].itemList = pl;
      //所在省
      this.initForm.find(item => item.fieldName==='customerProvince').itemList = pl;
      //上牌省份
      this.initForm.find(item => item.fieldName==='licenseProvinces').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId){
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
  
      let cl = this.createSubRegionList(this.cityData);
      //this.initForm[7].itemList = cl;
      //所在市
      this.initForm.find(item => item.fieldName==='customerCity').itemList = cl;
    },
    //初始化上牌市数据
    async initLicenseCity(provinceId){
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      let cd = rd[provinceId].children;
      let cl = this.createSubRegionList(cd);
      //this.initForm[21].itemList = cl;
      this.initForm.find(item => item.fieldName==='licenseCity').itemList = cl;
    },
    //初始化所在县市数据
    async initTown(cityId){
     
      if(!cityId || cityId==null || typeof(cityId)=='undefined'){
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      //this.initForm[8].itemList = tl;
      this.initForm.find(item => item.fieldName==='customerDistrict').itemList = tl;
    },
    //打开车型选择框
    openModelDialog() {
      this.visibleModelDlg = true;
    },
    //车型选择回显
    selectModelBack(data) {
      let modelNames = new Array();
      let modelIds = new Array();
      if(data && data.data && typeof(data.data)!=null && data.data.length>0){
        (data.data).forEach(models => {
          modelNames.push(models.modelName);//回显选择车型名称
          modelIds.push(models.modelId);//存储车型ID
        });
      }
      //this.initForm[14].initialValue = modelNames.join(",");
      this.initForm.find(item => item.fieldName==='intentionModelName').initialValue = modelNames.join(",");
      this.modelId = modelIds.join(",");
      this.visibleModelDlg =false; //关闭弹窗
    },
    //是否全国上牌选项变更，是：上牌省份可多选，上牌城市不可编辑；否：上牌省份和城市单选
    isLicenseAllChange(value){
        this.initForm.find(item => item.fieldName === 'licenseProvinces').initialValue = '';
        this.initForm.find(item => item.fieldName === 'licenseCity').itemList = [];
        this.initForm.find(item => item.fieldName === 'licenseCity').initialValue = '';
        if(value==10041001){//全国上牌
            //上牌城省多选
            this.initForm.find(item => item.fieldName === 'licenseProvinces').type = 'MULTIPLE_SELECT';
            //上牌城市不可编辑
            this.initForm.find(item => item.fieldName === 'licenseCity').disabled = true;
        }else{
            //上牌城省单选
            this.initForm.find(item => item.fieldName === 'licenseProvinces').type = 'SELECT';
            //上牌城市不可编辑
            this.initForm.find(item => item.fieldName === 'licenseCity').disabled = false;
        }
    }
  },
  mounted(){
    this.initProvince();
  }
}
</script>